package com.ytzl.controller;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ytzl.common.*;
import com.ytzl.model.ItripUser;
import com.ytzl.service.ItripUserService;
import com.ytzl.service.TokenService;
import com.ytzl.vo.TokenVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
@Slf4j
public class LoginController {

    @Autowired
    private ItripUserService itripUserService;

    @Autowired
    private TokenService tokenService;

    @PostMapping("/login")
    public ResponseData<ItripUser> userLogin(String userCode,String userPassword, HttpServletRequest request){

        //1.校验入参是否为空
        if (StringUtils.isEmpty(userCode)||StringUtils.isEmpty(userPassword)) {
            return ResponseDataUtils.buildError(CodeResultEnums.INPUT_PARAMS_IS_EMPTY);
        }else{
            //2.根据userCode和userPassword在数据库中查找该用户
            QueryWrapper<ItripUser> wrapper=new QueryWrapper<>();
            wrapper.eq("userCode",userCode).eq("userPassword", SecureUtil.md5(userPassword));
            ItripUser itripUser = itripUserService.getOne(wrapper);
            //3.判断该用户时候存在
            if (itripUser!=null){
                //4.创建token
                //"https://passport.baidu.com/passApi/js/wrapper.js?cdnversion=1632879258918&_=1632879256635"
                //String token = tokenService.createToken(request.getHeader("user-agent"), itripUser);
                String token=tokenService.createToken(request.getHeader("user-agent"), itripUser);
                //5.保存token
                tokenService.saveToken(token,itripUser);
                //6.将token返回给前端
                TokenVo tokenVo=new TokenVo();
                tokenVo.setToken(token);
                //token的过期时间=生成token的时间
                tokenVo.setExpireTime(Calendar.getInstance().getTimeInMillis()+Constants.SESSION_EXPIRE*1);
                tokenVo.setCreationTime(Calendar.getInstance().getTimeInMillis());
                return ResponseDataUtils.buildSuccess(tokenVo);
            }else{
                return ResponseDataUtils.buildError(CodeResultEnums.USER_NOT_EXSITS);
            }
        }
    }

    @PostMapping("/JWTlogin")
    public Map<String,Object> login(@RequestBody ItripUser userForm){
        log.info("用户名:[{}]",userForm.getUsercode());
        log.info("密码:[{}]",userForm.getUserpassword());

        Map<String,Object> map = new HashMap<>();
        try{
            ItripUser userDB = this.findUserByCondition(userForm);
            Map<String,String> payload = new HashMap<>();
            payload.put("userId",userDB.getId().toString());
            payload.put("userName",userDB.getUsername());
            payload.put("userCode",userDB.getUsercode());

            //生成token令牌
            String token = JwtUtils.createToken(payload);

            log.info("userDB:[{}]",userDB);
            map.put("state",true);
            map.put("msg","登录成功");
            map.put("token",token);
        }catch (Exception e){
            map.put("state",false);
            map.put("msg",e.getMessage());
        }
        return map;
    }

    public ItripUser findUserByCondition(ItripUser user){
        QueryWrapper<ItripUser> params = new QueryWrapper<ItripUser>();
        params.eq("userCode",user.getUsercode());
        params.eq("userPassword",SecureUtil.md5(user.getUserpassword()));

        return  itripUserService.getOne(params);
    }

}
